const envConfig = require('./config/env')

App({
  onLaunch: function () {
    console.log('小程序启动')
    console.log('当前环境:', envConfig.currentEnv)
    console.log('API地址:', envConfig.baseUrl)
    
    // 检查是否有登录态
    this.checkLoginStatus()
    
    // 获取用户信息
    this.getUserProfile()
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token')
    const userInfo = wx.getStorageSync('userInfo')
    
    if (token && userInfo) {
      this.globalData.isLogin = true
      this.globalData.userInfo = userInfo
      this.globalData.token = token
    } else {
      this.globalData.isLogin = false
    }
  },

  // 获取用户信息
  getUserProfile() {
    // 检查是否授权过用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: res => {
              this.globalData.wxUserInfo = res.userInfo
            }
          })
        }
      }
    })
  },

  // 设置登录状态
  setLoginStatus(userInfo, token) {
    this.globalData.isLogin = true
    this.globalData.userInfo = userInfo
    this.globalData.token = token
    
    // 存储到本地
    wx.setStorageSync('userInfo', userInfo)
    wx.setStorageSync('token', token)
  },

  // 清除登录状态
  clearLoginStatus() {
    this.globalData.isLogin = false
    this.globalData.userInfo = null
    this.globalData.token = null
    this.globalData.wxUserInfo = null
    
    // 清除本地存储
    wx.removeStorageSync('userInfo')
    wx.removeStorageSync('token')
  },

  globalData: {
    isLogin: false,
    userInfo: null,
    token: null,
    wxUserInfo: null,
    baseUrl: envConfig.baseUrl // 使用环境配置中的baseUrl
  }
}) 